package com.itheima.service.impl;

import com.fasterxml.jackson.core.JsonProcessingException;
import com.fasterxml.jackson.databind.ObjectMapper;
import com.itheima.dao.CategoryDao;
import com.itheima.domain.Category;
import com.itheima.util.JedisUtils;
import com.itheima.factory.BeanFactory;
import com.itheima.service.CategoryService;
import com.itheima.util.MyBatisUtils;
import org.apache.ibatis.session.SqlSession;
import redis.clients.jedis.Jedis;

import java.io.IOException;
import java.util.List;

public class CategoryServiceImpl implements CategoryService {

    @Override
    public List<Category> findAll() {
        ObjectMapper objectMapper=new ObjectMapper();
        List<Category> categoryList = null;
        //1.先查缓存
        Jedis jedis = JedisUtils.getJedis();
        //2.判断是否有导航分类缓存
        if (jedis.exists("travel_category")) {
            //存在查询缓存
            String json = jedis.get("travel_category");

            //将json转换为java对象
            try {
                categoryList = objectMapper.readValue(json, List.class);

                System.out.println("从redis中查询...");
            } catch (IOException e) {
                e.printStackTrace();
            }
        } else {
            //不存在，查询数据库
            // 获取代理对象
            SqlSession sqlSession = MyBatisUtils.openSession();
            CategoryDao categoryDao = sqlSession.getMapper(CategoryDao.class);

            categoryList = categoryDao.findAll();

            System.out.println("从sql查询...");
            // 关闭会话
            MyBatisUtils.close(sqlSession);
           //同步到redis中
            try {
                String json = objectMapper.writeValueAsString(categoryList);

                jedis.set("travel_category",json);
            } catch (JsonProcessingException e) {
                e.printStackTrace();
            }
        }
        // 归还jedis到连接池
        jedis.close();
        return categoryList;
    }

}
